<template>
  <a-select
    v-model:value="value"
    :loading="loading"
    :options="remoteUnitData"
    :field-names="{ label: 'unitName', value: 'id' }"
    :filter-option="filterOption"
    show-search
    v-bind="attrs"
  />
</template>

<script setup>
  // this对象
  import { getCurrentInstance, ref, useAttrs, watch } from 'vue';
  import * as productApi from '@/api/base-data/product/info';

  defineOptions({
    name: 'ProductUnitSelect',
  });

  const instance = getCurrentInstance();

  const loading = ref(false);

  const value = defineModel('value', {
    type: [String, Array],
    required: true,
  });

  const props = defineProps({
    productId: {
      type: String,
      default: '',
    },
  });

  const attrs = useAttrs();

  const remoteUnitData = ref([]);

  const filterOption = (input, option) => {
    return option.value.toLowerCase().indexOf(input.toLowerCase()) >= 0;
  };

  const loadUnitData = () => {
    loading.value = true;
    productApi
      .getUnitByProductId(props.productId)
      .then((data) => {
        remoteUnitData.value = data;
      })
      .finally(() => (loading.value = false));
  };

  // 组件实例对象
  const _This = () => {
    return instance.appContext.config.globalProperties;
  };

  watch(
    () => props.productId,
    (value) => {
      if (_This().$utils.isEmpty(value)) {
        remoteUnitData.value = [];
      } else {
        loadUnitData();
      }
    },
    { immediate: true },
  );
</script>

<style scoped></style>
